import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:image_picker/image_picker.dart';

class AddMaterial extends StatefulWidget {
  final Map item;
  final onSubmit;

  AddMaterial({Key key, this.item, this.onSubmit}) : super(key: key);

  @override
  State<StatefulWidget> createState() => AddMaterialState();
}

class AddMaterialState extends State<AddMaterial> {
  int materialTypeId;
  String materialTypeName;
  List uploadList = [];
  List locatUploadList = [];
  String baseApi = '/enter';

  final picker = ImagePicker();
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _numController = new TextEditingController();
  TextEditingController _typesController = new TextEditingController();
  TextEditingController _unitController = new TextEditingController();
  TextEditingController _remarkController = new TextEditingController();

  var eventBus = new EventBus();

  @override
  void initState() {
    super.initState();
    // 监听物资分类选择
    eventBus.on("enter_mct", (parmas) {
      var p = parmas['select'];
      setState(() {
        materialTypeId = p['id'];
        materialTypeName = p['name'];
      });
    });
  }

  // 添加物资
  _addMaterial() {
    var name = _nameController.text.trim();
    var typeId = materialTypeId;
    var number = _numController.text.trim();
    var types = _typesController.text.trim();
    var unit = _unitController.text.trim();
    var remark = _remarkController.text.trim();

    if (name.isEmpty) {
      Utils.showText(text: '请输入物资名称', align: Alignment(0, 0));
      return;
    }
    if (typeId == null) {
      Utils.showText(text: '请选择物资类型', align: Alignment(0, 0));
      return;
    }
    if (number.toString().isEmpty) {
      Utils.showText(text: '请输入物资数量', align: Alignment(0, 0));
      return;
    }

    Map data = {
      'name': name,
      'type_id': typeId,
      'typeName': materialTypeName,
      'num': number,
      'specification': types,
      'unit': unit,
      'remark': remark,
    };

    widget.onSubmit(data);
    Navigator.pop(context);
  }

  Widget _buildDialogHead(title) {
    return Container(
      height: 80.w,
      decoration: BoxDecoration(
          color: Utils.hexToColor('#F7F7F7'),
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.w), topRight: Radius.circular(12.w))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: 31.w),
            child: Text(title,
                style: TextStyle(
                    color: Utils.hexToColor('#333333'),
                    fontSize: 16,
                    fontWeight: FontWeight.bold)),
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(30.w, 24.w, 30.w, 24.w),
              alignment: Alignment.topRight,
              child: Image.asset(
                'assets/dialog_close.png',
                width: 36.w,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildInput(title, controller, [isNumber = false, maxLines = 1]) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 160.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
            width: 460.w,
            height: maxLines > 1 ? 200.h : 70.h,
            child: TextField(
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    RegExp(isNumber ? '[0-9]' : '[^]')),
              ],
              maxLines: maxLines,
              controller: controller,
              style: TextStyle(fontSize: 14, color: Colors.black), //输入文本的样式
              decoration: InputDecoration(
                hintText: "请输入" + title,
                hintStyle: TextStyle(color: Color(0xFFC8C8D9), fontSize: 14),
                contentPadding: EdgeInsets.fromLTRB(21.w, 10, 21.w, 10),
                fillColor: Colors.white,
                filled: true,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSelectInput(title, value) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: 160.w,
            height: 40,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, "/material_type",
                  arguments: {'baseApi': baseApi});
            },
            child: Container(
              width: 460.w,
              height: 40,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  border:
                      Border.all(color: Utils.hexToColor('#D2D2D2'), width: 1)),
              child: Container(
                child: Text(value.toString(),
                    style: TextStyle(
                        color: Utils.hexToColor(
                            (materialTypeName == '请选择物资类型' ||
                                    materialTypeName == null)
                                ? '#CBCACF'
                                : '#0000000'),
                        fontSize: 14)),
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Container(
        width: 700.w,
        height: 1161.w,
        decoration:
            BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(100))),
        child: Column(
          children: <Widget>[
            _buildDialogHead('物资信息'),
            Expanded(
              flex: 1,
              child: SingleChildScrollView(
                child: Container(
                    padding: EdgeInsets.all(40.w),
                    child: Column(
                      children: <Widget>[
                        _buildInput('物资名称', _nameController),
                        _buildSelectInput(
                            '物资类型',
                            materialTypeName == null
                                ? '请选择物资类型'
                                : materialTypeName),
                        _buildInput('物资数量', _numController, true),
                        _buildInput('规格/型号', _typesController),
                        _buildInput('单位', _unitController),
                        _buildInput('备注', _remarkController, false, 5),
                      ],
                    )),
              ),
            ),
            Container(
              height: 120.w,
              // color: Utils.hexToColor('#FFFFFF'),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          width: 1, color: Utils.hexToColor('#F2F2F2')))),
              child: SizedBox(
                width: 620.w,
                height: 76.w,
                child: ElevatedButton(
                  onPressed: () {
                    _addMaterial();
                  },
                  child: Text(
                    '保存',
                    style: TextStyle(color: Colors.white),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF297CFF),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(60.w))),
                  ),
                ),
              ),
            )
          ],
        ));
  }
}
